package com.yc.demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.demo.aop.HelloInterceptor;
import com.yc.demo.listener.HelloSessionListener;
import com.yc.demo.util.JsonUtil;

import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>Web启动配置</p>
 * <pre>
 *     1.添加拦截器
 * </pre>
 *
 * @version 1.0
 * @author:Yuan childe
 * @date:2017/11/16 001615:56
 * @history
 */
@Slf4j
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = JsonUtil.getObjectMapper();
        jsonConverter.setObjectMapper(objectMapper);
        return jsonConverter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(customJackson2HttpMessageConverter());
    }

    /**
     * 过滤器另外一种方式
     * @return
     */
/*    @Bean
    public FilterRegistrationBean filterRegist() {
        FilterRegistrationBean frBean = new FilterRegistrationBean();
        frBean.setFilter(new HelloFilter());
        frBean.addUrlPatterns("/*");
        return frBean;
    }*/

    @Bean
    public ServletListenerRegistrationBean listenerRegist() {
        ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
        srb.setListener(new HelloSessionListener());
        return srb;
    }

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        registry.addInterceptor(new HelloInterceptor()).addPathPatterns("/api/**");
    }
}
